/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package conexion;

import elementos.Composite;
import elementos.Drawable;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pedro
 */
public class ConectarFase implements ConexionServidor{
    private String sid="";

    public URLConnection getConnection(){
        try {
            String location = "http://localhost:8080/web/PhaseServlet";
            URL url = new URL(location);
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            connection.setRequestProperty("Cookie", "JSESSIONID="+sid);
            return connection;
        } catch (IOException ex) {
            Logger.getLogger(ConectarRanking.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
    @Override
    public Drawable loadPhase(int p) {
        try {
            URL url;
            URLConnection connection = getConnection();
            //escribimos al buffer
            OutputStream outstream;
            outstream = connection.getOutputStream();
            ObjectOutputStream s = new ObjectOutputStream(outstream);
            //identificador para el servlet
            s.writeObject(p);
            s.flush();
            s.close();
            //leemos del buffer la comprobación
            InputStream instream = connection.getInputStream();
            ObjectInputStream j = new ObjectInputStream(instream);
            Composite escena = (Composite) j.readObject();
            sid=(String)j.readObject();
            j.close();
            return escena;
        } catch (Exception ex) {
            Logger.getLogger(ConectarFase.class.getName()).log(Level.SEVERE, null, ex);
            return null;
    }
    }
    
}
